﻿@inherits SsoSectionComponentBase
@inject EnvironmentDataService EnvironmentData

<MTextField PrependInnerIcon="mdi-cellphone" Value="Value.PhoneNumber" TValue="string" ValueChanged="ValueChangeHandler" Label="@T("PhoneNumber")"
            Placeholder="@T("PhoneNumberPlaceholder")" Outlined @ref="_phoneTextField" Rules="_phoneNumberRules">
</MTextField>
<CaptchaSendTextField Class="mt-3" @bind-Value="Value.SmsCode" OnClick="GetSmsCode" />

@code {
    [Parameter]
    public RegisterInputModel Value { get; set; } = new();

    [Parameter]
    public EventCallback<RegisterInputModel> ValueChanged { get; set; }

    [Parameter]
    public bool Required { get; set; } = true;

    MTextField<string> _phoneTextField = null!;

    [Inject]
    public IAuthClient AuthClient { get; set; } = null!;

    private IList<Func<string, StringBoolean>> _phoneNumberRules = new List<Func<string, StringBoolean>>();

    protected override Task OnParametersSetAsync()
    {
        if (!_phoneNumberRules.Any())
        {
            _phoneNumberRules.Add(value => Regex.Match(value, LoginOptions.PhoneRegular).Success ? true : T("PhoneNumberPrompt"));
        }        
        if (Required && _phoneNumberRules.Count == 1)
        {
            _phoneNumberRules.Add(value => !string.IsNullOrEmpty(value) ? true : T("PhoneRequired"));
        }

        return base.OnParametersSetAsync();
    }

    private async Task<bool> GetSmsCode()
    {
        if (_phoneTextField.Validate())
        {
            await AuthClient.UserService.SendMsgCodeAsync(new SendMsgCodeModel
            {
                SendMsgCodeType = SendMsgCodeTypes.Register,
                PhoneNumber = Value.PhoneNumber,
                Environment = EnvironmentData.Environment
            });
        }
        return _phoneTextField.Validate();
    }

    void ValueChangeHandler(string value)
    {
        Value.PhoneNumber = value;
    }
}
